import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Message, Upload, Dialog, Tab } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { column, toSelectDataSource, ENUMS } from './stores/definitions';
import { toJS } from 'mobx';
import BaseModal from './components/BaseModal';
import DrawerComponents from './components/DrawerComponents';
import QR from './components/QR';
import CompanyInputDialog from './components/CompanyInputDialog';
import MoreFuncDropDown from '@/components/MoreFuncDropDown';

const tableId = uniqueId('tauTable-');

const Member = () => {
  const [modal, setModal] = useState({
    show: null,
    record: null,
  });
  const [uploading, setUploading] = useState(false);
  const { memberStore: store, ruleStore, loginStore } = useStore();
  const { isAdmin } = loginStore;
  const [companyInputDialogVisible, setCompanyInputDialogVisible] = useState(false);
  const dialogRef = useRef();

  useEffect(() => {
    store.search = {
      groupIds: [ruleStore._group_id],
    };
    (async () => {
      await store.getCompaniesNames();
    })();
  }, [ruleStore._group_id]);

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { getOnDate, takeOrderStatus: status, ...searchArgs } = params.values;
    const [from, to] = getOnDate || [];
    store.search = {
      from,
      to,
      groupIds: [ruleStore._group_id],
      ...searchArgs,
      ...(status ? { takeOrderStatus: JSON.parse(status) } : {}),
    };
  };

  const handleAddMember = () => {
    setModal({ show: 'add', record: null });
  };

  const handleOpenView = (record) => {
    setModal({ show: 'view', record });
  };

  const handleUpdateFile = ({ file, onSuccess, onError }) => {
    const { uid, type, name } = file;
    const reader = new FileReader();
    reader.onloadend = async () => {
      setUploading(true);
      try {
        if (type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
          Message.error(t`白名单文件格式错误.`);
          return;
        }
        await store.filesUpload({
          binary: {
            binaryId: uid,
            mimeType: type,
            filename: name,
          },
        }, Buffer.from(reader.result));
        await store.importing(uid, { groupId: ruleStore._group_id });
        onSuccess?.(file);
        Message.success(t`白名单上传成功`);
      } catch (e) {
        onError?.(e);
        Message.error(t`白名单上传失败`);
      } finally {
        setUploading(false);
      }
    };
    reader.readAsArrayBuffer(file);
  };

  const handleDownload = async () => {
    await store.download();
  };

  const handleOnBackup = () => {
    const findGroup = ruleStore?._groups.find((p) => p.value === ruleStore?._group_id);
    setModal({
      show: 'backup',
      record: {
        groupInfo: toJS(findGroup),
      },
    });
  };

  const handleOnEdit = (result) => {
    setModal({ show: 'edit', record: result });
  };

  const handleOnRemove = async (result) => {
    if (!_.isEmpty(result)) {
      const verifyInfo = await store._verifyRemove(result);
      Dialog.confirm({
        content: verifyInfo?.value ? ENUMS._WARN_TEXT[verifyInfo?.type] : t`确定删除吗？`,
        onOk: async () => {
          try {
            const { id } = toJS(result);
            await store.remove(id);
            await store.getCompaniesNames();
            Message.success({ content: t`删除成功` });
          } catch (e) {
            Message.error({ content: t`删除失败`, duration: 7000 });
            throw e;
          }
        },
      });
    }
    handleCancel();
  };

  const handleCancel = () => {
    setModal({ show: null, record: null, type: null });
  };

  const handleOnSubmit = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.create(toJS(result));
        await store.getCompaniesNames();
        Message.success({ content: t`添加成功` });
      } catch (e) {
        Message.error({ content: t`${e?.source?.message}`, duration: 7000 });
        throw e;
      }
    }
    handleCancel();
  };

  const handelOnUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.update(toJS(result));
        await store.getCompaniesNames();
        Message.success({ content: t`编辑成功` });
      } catch (e) {
        Message.error({ content: t`${e?.source?.message}`, duration: 7000 });
        throw e;
      }
    }
    handleCancel();
  };

  const handleApprove = () => {
    setCompanyInputDialogVisible(true);
  };

  const handleCompanyInputDialogConfirm = async (info) => {
    setCompanyInputDialogVisible(false);
    // 在这里继续执行审核通过的逻辑
    const { id, type } = dialogRef.current;
    await passMember(id, type, info);
  };

  const handleCompanyInputDialogCancel = () => {
    setCompanyInputDialogVisible(false);
  };

  const handleOnPass = async (result) => {
    // if (!_.isEmpty(result)) {
    // const { id, type } = toJS(result);
    // dialogRef.current = toJS(result);
    // if (type === '0') {
    //   handleApprove(id);
    //   return;
    // }
    await passMember(result?.id);
    // }
    // handleCancel();
  };

  async function passMember(id) {
    Dialog.confirm({
      content: t`确定通过该成员审核吗？`,
      onOk: async () => {
        try {
          await store.passCheck(id);
          Message.success({ content: t`操作成功` });
        } catch (e) {
          Message.error({ content: t`${e?.source?.message}`, duration: 7000 });
          throw e;
        }
        handleCancel();
      },
    });
  }

  const handleViewOrder = (record, type) => {
    setModal({ show: 'order', record, type });
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={[
          {
            name: 'btn-member',
            title: t`添加成员`,
            type: 'primary',
            onClick: handleAddMember,
          },
          {
            name: 'btn-placeRule',
            component: (
              <Upload
                accept=".xlsx"
                onSuccess={() => store.query()}
                request={handleUpdateFile}
              >
                <Button type="primary" loading={uploading}>{t`上传白名单`}</Button>
              </Upload>
            ),
          },
          {
            name: 'btn-download',
            title: t`下载白名单模板`,
            type: 'primary',
            onClick: handleDownload,
          },
          {
            name: 'btn-backup',
            title: t`备案二维码`,
            type: 'primary',
            onClick: handleOnBackup,
          },
        ].filter((p) => {
          // 合并过滤条件
          if (isAdmin) return true;
          return p.name === 'btn-member' || p.name === 'btn-backup';
        })}
        searchItems={
          [
            {
              name: 'getOnDate',
              type: 'date-range',
              props: {
                placeholder: [t`开始创建时间`, t`结束创建时间`],
              },
            },
            {
              name: 'type',
              type: 'select',
              props: {
                dataSource: toSelectDataSource(ENUMS.type),
                placeholder: t`类型`,
              },
            },
            {
              name: 'takeOrderStatus',
              type: 'select',
              props: {
                dataSource: toSelectDataSource(ENUMS.takeOrderStatus),
                placeholder: t`接单状态`,
              },
            },
            {
              name: 'ports',
              type: 'dict-item',
              props: {
                dictId: 'port',
                placeholder: t`车辆口岸`,
                mode: 'multiple',
              },
            },
            {
              name: 'companyName',
              type: 'select',
              props: {
                placeholder: t`公司名称`,
                dataSource: store.companiesNames,
                style: { width: 160 },
              },
            },
          ]}
        keywordSearch={{
          // enabled: true,
          placeholder: t`请输入关键字搜索`,
        }}
        className="action-panel"
      />
      <div className="content">
        <Tab
          defaultActiveKey={'-1'}
          activeKey={store._tableStatus}
          onChange={(v) => {
            store.data = [];
            store.table_Status = v;
          }}
        >
          {store._tabItems?.map((item) => (<Tab.Item key={item.key} title={item.label} />))}
        </Tab>
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.data)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('id', {
              width: 88,
              cell: (v, __, r) => <Button type="primary" text onClick={() => handleOpenView(r)}>{v}</Button>,
            }),
            column('nameGroup', { width: 99 }),
            column('fullname', { width: 88 }),
            column('phone', { width: 110 }),
            column('type', { width: 88 }),
            column('issueOrderCount', {
              width: 88,
              cell: (v, __, r) => {
                return (
                  <Button type="primary" text onClick={() => handleViewOrder(r, 'publish')}>{v}</Button>
                );
              },
              sortable: true,
            }),
            column('takeOrderCount', {
              width: 88,
              cell: (v, __, r) => {
                return (
                  <Button type="primary" text onClick={() => handleViewOrder(r, 'take')}>{v}</Button>
                );
              },
              sortable: true,
            }),
            column('points', {
              width: 88,
              sortable: true,
            }),
            column('takeOrderStatus', { width: 100 }),
            column('status', { width: 100 }),
            column('crDate', { width: 126, sortable: true }),
            {
              title: t`操作`,
              dataIndex: 'memberNumber',
              width: 120,
              cell: (_, __, r) => {
                const data = [
                  {
                    title: t`编辑`,
                    onClick: () => handleOnEdit(r),
                  },
                  {
                    title: t`删除`,
                    onClick: () => handleOnRemove(r),
                    color: 'red',
                  },
                ];
                if (store._tableStatus == '-1') {
                  data.push(
                    {
                      title: t`通过`,
                      onClick: () => handleOnPass(r),
                    },
                  );
                }
                if (!isAdmin && store._tableStatus !== '-1') data.filter((p, i) => i !== 1);
                return <MoreFuncDropDown dropdownItems={data} maxShow={1} />;
              },
            },
          ]}
        />
      </div>
      <BaseModal
        modal={modal}
        setModal={setModal}
        onCancel={handleCancel}
        onSubmit={modal.show == 'add' ? handleOnSubmit : handelOnUpdate}
        onPass={handleOnPass}
      />
      <DrawerComponents model={modal} onCancel={handleCancel} />
      <QR modal={modal} />
      <CompanyInputDialog
        visible={companyInputDialogVisible}
        info={dialogRef.current}
        onClose={handleCompanyInputDialogCancel}
        onConfirm={handleCompanyInputDialogConfirm}
      />
    </TauPage>
  );
};

export default observer(Member);
